<?php
namespace app\api\controller;

use app\common\Tools as CommonTools;
use app\model\Cassette;
use app\model\Merchant as ModelMerchant;
use app\model\MerchantCate;
use app\model\OrderMembers;
use app\model\Orders;
use app\Request;
use app\services\RedisService;
use think\db\Query;
use think\facade\Db;

//订单
class Order extends ApiBase
{

  

    //开局
    public function create_order(Request $request){
        Db::startTrans();
        try {
            $post_data = $request->postMore([
                ['mid', 0],
                ['cid', 0],
                ['play_mode', ''],
                ['requirements', ''],
                ['contact_name', ''],
                ['contact_mobile', ''],
                ['max_people', ''],
                ['start_time', ''],
                ['start_date', ''],
                ['remark', ''],
            ]);
            CommonTools::check($post_data, [
                'mid' => 'require',
                'cid' => 'require',
                'contact_name' => 'require',
                'contact_mobile' => 'require|mobile',
                'start_date' => 'require',
                'start_time' => 'require',
            ]);
            $start_date = $post_data['start_date'].' '.$post_data['start_time'];
            if(!$merchant = ModelMerchant::where('id',$post_data['mid'])->where('status',1)->find()){
                throw new \Exception('商家不存在或已下架');
            }
            if(!$cassette = Cassette::where('mid',$post_data['mid'])->where('id',$post_data['cid'])->where('status',1)->find()){
                throw new \Exception('卡座信息不存在');
            }
            if($post_data['max_people'] > $cassette->max_num){
                throw new \Exception('超过卡座最高人数限制');
            }
             if(Orders::where('uid',$this->get_user_id())->where('mid',$post_data['mid'])->where('cid',$post_data['cid'])->where('status',1)->count()){
                throw new \Exception('当前卡座您已经有一个进行中的组局信息了');
             }
             $user_info = $this->get_user_info();
             $insert_data = $post_data;
             $insert_data['uid']             = $user_info['id'];
             $insert_data['nickname']        = $user_info['nickname'];
             $insert_data['avatar']          = $user_info['avatar'];
             $insert_data['merchant_name']   = $merchant->name;
             $insert_data['cassette_name']   = $cassette->name;
             $insert_data['start_time']      = $start_date;
             $insert_data['join_people']     = 1;
             $insert_data['start_timestamp'] = strtotime($start_date);
             $order = Orders::create($insert_data);
             OrderMembers::create([
                'mid'  => $post_data['mid'],
                'cid'  => $post_data['cid'],
                'oid'  => $order->id,
                'uid'  => $user_info['id'],
                'nickname' => $user_info['nickname'],
                'avatar'  => $user_info['avatar'],
                'is_leader' => 1,
                'status'    => 1
             ]);
             Db::commit();
        } catch (\Exception $e) {
             Db::rollback();
            return app('json')->fail($e->getMessage());
        }
        return app('json')->success('ok',$order->id);
    }


    //组局详情
    public function order_detail(Request $request){
        $data = $request->getMore([
            ['order_id', 0]
        ]);
        if(!$data['order_id'] > 0) return app('json')->fail('Id不得为空');
        $detail = Orders::with(['merchant'=>function(Query $query){
            $query->append(['is_open']);
        },'cassette','members'])->where('id',$data['order_id'])->find();
        $detail->is_join = OrderMembers::where('oid',$detail->id)->count() ? true : false;
        if($detail->start_timestamp <= time()){
            $detail->status = 3;
            $detail->save();
            OrderMembers::where('oid',$detail->id)->update(['status'=>2]);
        }
        return app('json')->success('ok',$detail);
    }


    //加入组局
    public function join_group(Request $request){
        $redis_server = RedisService::getInstance();
        $key          = 'join_group'.$this->get_user_id();
        Db::startTrans();
        try {
            $data = $request->postMore([
                ['order_id', 0]
            ]);

            if($redis_server->setnx($key,1)) {
                throw new \Exception('网络拥挤清稍后');
            }
           if(!$order = Orders::find($data['order_id'])){
                throw new \Exception('组局不存在');
           }
           if($order->status !=1){
                throw new \Exception('当前不可加入');
           }
           if($order->join_people >= $order->max_people){
                throw new \Exception('当前组局已满人');
           }
           if($order->start_timestamp <=time()){
                throw new \Exception('当前组局时间已结束');
            }
            if(OrderMembers::where('oid',$order->id)->where('uid',$this->get_user_id())->count()){
                throw new \Exception('您已经加入该组局了');
            }
            $user_info = $this->get_user_info();
            OrderMembers::create([
                'mid'       => $order['mid'],
                'cid'       => $order['cid'],
                'oid'       => $order->id,
                'uid'       => $user_info['id'],
                'nickname'  => $user_info['nickname'],
                'avatar'    => $user_info['avatar'],
                'is_leader' => 0,
                'status'    => 1
             ]);
             $order->join_people +=1;
             if($order->join_people >= $order->max_people){
                $order->status = 2;
                OrderMembers::where('oid',$order->id)->update(['status'=>2]);
             }
             $order->save();
           Db::commit();
        } catch (\Exception $e) {
           Db::rollback();
           return app('json')->fail($e->getMessage());
        }
        $redis_server->delete($key);
        return app('json')->success('ok');
    }


    //组局列表
    public function group_list(Request $request){
        $search = $request->getMore([
            ['page', 1],
            ['limit', 10],
            ['cate_id', 0],
        ]);
        $where = [];
        $where[] = ['status','=',1];
        if($search['cate_id'] > 0){
            $mids = ModelMerchant::where('cate_id',$search['cate_id'])->where('status',1)->column('id');
            $where[] = ['mid','in',$mids];
        }
        $list = Orders::with(['merchant'=>function(Query $query){
            $query->append(['is_open']);
        },'cassette','members'])->where($where)->order('sort desc')->page($search['page'],$search['limit'])->select();
        return app('json')->success('ok',$list);
    }
}